import store from "@/store"
import Vue from "vue"
import VueRouter, { RouterLink } from "vue-router"
import routes from "./routes"

// 使用vuerouter
Vue.use(VueRouter)

// 原型上修改push方法
const originPush = VueRouter.prototype.push  // 先将之前的存储到一个变量当中
// 修改VueRouter原型上的push 用于解决重复跳转时报错的问题
VueRouter.prototype.push = function (location, okCallBack, errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 上面的判断成立的话，表示没有传递这两个参数
    originPush.call(this, location).catch(() => { })  // 统一处理报错的问题 
  } else {
    originPush.call(this, location, okCallBack, errCallBack)
  }
}


let router = new VueRouter({
  mode: "history",
  routes,
  // 解决跳转路由时滚动条的位置
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})
let WhiteList = [
  "home",
  "search",
  "register",
  "detail",
  "login",
  "addcarsuccess",
  "shopcart"
]

// 路由全局前置守卫
router.beforeEach((to, from, next) => {
  if (WhiteList.includes(to.name) || store.state.login.userInfo.token) {
    next()
    return
  }
  next({
    name: "login",
    query: {
      redirect: to.path
    }
  })


})

export default router

